﻿/*-------------------------------------------------------------------------
* 命名空间: YiDunXray.Common/WpfHelper
* 类       名: WpfHelper
* 功      能:  TD
* 时      间:  2024-07-03 10:42:50
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace XrayDirection.Common
{
    public class WpfHelper
    {
        private bool _gcTaskIsAlive = false;

        public void GcTaskStart(int gcDuration)
        {
            if (_gcTaskIsAlive) return;
            Task.Run(() =>
            {
                DoGcTask(gcDuration);
            });
        }

        [DllImport("kernel32.dll")]
        private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);

        public void DoGcTask(int gcDuration)
        {
            _gcTaskIsAlive = true;
            while (_gcTaskIsAlive)
            {
                // 强制进行垃圾回收
                GC.Collect();
                // 等待所有挂起终结器运行完成
                GC.WaitForPendingFinalizers();
                //如果是运行在windows平台上
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    // 将当前进程的工作集大小设置为默认值
                    SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
                }
                Thread.Sleep(TimeSpan.FromSeconds(gcDuration));
            }
        }

        public void GcTaskStop()
        {
            _gcTaskIsAlive = false;
        }

    }
}
